package com.mo.axion.service.api.impl.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.mo.axion.common.constant.AxionConstant;
import com.mo.axion.common.domain.SimpleAnchorInfo;
import com.mo.axion.common.enums.RespStatusEnum;
import com.mo.axion.domain.TraceResponse;
import com.mo.axion.service.TraceService;
import com.mo.axion.support.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mo
 * @createTime 2024/4/13 15:41
 * @description 链路追踪查询实现类
 */
@Service
public class TraceServiceImpl implements TraceService {

    @Autowired
    private RedisUtils redisUtils;
    /**
     * 基于消息Id 查询链路结果
     *
     * @param messageId
     * @return
     */
    @Override
    public TraceResponse traceByMessageId(String messageId) {
        if (CharSequenceUtil.isBlank(messageId)) {
            return new TraceResponse(
                    RespStatusEnum.CLIENT_BAD_PARAMETERS.getCode(),
                    RespStatusEnum.CLIENT_BAD_PARAMETERS.getMsg(),
                    null
            );
        }
        String redisMessageKey = CharSequenceUtil.join(StrUtil.COLON, AxionConstant.CACHE_KEY_PREFIX, AxionConstant.MESSAGE_ID, messageId);
        List<String> messageList = redisUtils.lRange(redisMessageKey, 0, -1);
        if (CollUtil.isEmpty(messageList)) {
            return new TraceResponse(
                    RespStatusEnum.FAIL.getCode(),
                    RespStatusEnum.FAIL.getMsg(),
                    null
            );
        }

        List<SimpleAnchorInfo> sortAnchorList = messageList.stream().map(s -> JSON.parseObject(s, SimpleAnchorInfo.class)).sorted((o1, o2) -> Math.toIntExact(o1.getTimestamp() - o2.getTimestamp())).collect(Collectors.toList());
        return new TraceResponse(
                RespStatusEnum.SUCCESS.getCode(),
                RespStatusEnum.SUCCESS.getMsg(),
                sortAnchorList
        );
    }
}
